package com.wind.plugin.window;

import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.openapi.project.*;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.*;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.XmlFile;
import com.intellij.ui.components.JBTabbedPane;
import com.intellij.util.indexing.FileBasedIndex;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static com.wind.plugin.window.Utils.countMissingTInXmlFile;
import static com.wind.plugin.window.Utils.countSumOccurrencesInXmlFile;

public class MapperCheckWindowPanel extends JPanel {
    private final Project project;
    private MissImCustNoPanel missImCustNoPanel;
    private AggCountPanel aggCountPanel;

    private VirtualFileManager virtualFileManager;


    private boolean showMissingT = true; // Flag to indicate which info to show


    public MapperCheckWindowPanel(Project project) {
        this.project = project;

        this.missImCustNoPanel = new MissImCustNoPanel(project);
        this.aggCountPanel = new AggCountPanel(project);


        setLayout(new GridLayout(1,1,1,1));

        JBTabbedPane jbTabbedPane = new JBTabbedPane();

        jbTabbedPane.add("缺失imCustNo", missImCustNoPanel);
        jbTabbedPane.add("函数使用情况", aggCountPanel);

        add(jbTabbedPane);

        jbTabbedPane.setSelectedIndex(0);


        // 添加选中事件监听器
        jbTabbedPane.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                int selectedIndex = jbTabbedPane.getSelectedIndex();
                System.out.println("Selected Index: " + selectedIndex);

                // 根据选中的索引执行相应的操作
                switch (selectedIndex) {
                    case 0:
                        // 执行选项卡1的操作
                        showMissingTFields();
                        break;
                    case 1:
                        // 执行选项卡2的操作
                        showSumOccurrences();
                        break;
                    case 2:
                        // 执行选项卡3的操作
                        break;
                    default:
                        break;
                }
            }
        });



        virtualFileManager = VirtualFileManager.getInstance();
        virtualFileManager.addVirtualFileListener(new VirtualFileAdapter() {
            @Override
            public void contentsChanged(@NotNull VirtualFileEvent event) {
                // Check if the modified file is a mapper.xml file
                // 处理分支切换时，容器被销毁的情况
                if (project != null && !project.isDisposed()) {
                    try {
                        ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
                        // 现在可以安全地使用 fileIndex
                        if ("xml".equalsIgnoreCase(event.getFile().getExtension()) &&
                                fileIndex.isInSourceContent(event.getFile())) {
                            // Update UI when XML file content changes
                            analyzeMapperXmlFiles();
                        }
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                } else {
                    // 处理项目无效的情况，可能需要重新获取项目引用或者进行其他处理
                }
            }
        });

        // Analyze mapper.xml files
        analyzeMapperXmlFiles();
    }

    private void analyzeMapperXmlFiles() {
        SwingUtilities.invokeLater(() -> {
            Map<String, Integer> fileToMissingTCount = new HashMap<>();
            Map<String, Integer> fileToSumCount = new HashMap<>();

            PsiManager psiManager = PsiManager.getInstance(project);
            Collection<VirtualFile> xmlFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, XmlFileType.INSTANCE, GlobalSearchScope.allScope(project));

            for (VirtualFile file : xmlFiles) {
                if (ProjectRootManager.getInstance(project).getFileIndex().isInSourceContent(file)) {
                    PsiFile psiFile = psiManager.findFile(file);
                    if (psiFile instanceof XmlFile) {
                        int missingTCount = countMissingTInXmlFile((XmlFile) psiFile);
                        int sumCount = countSumOccurrencesInXmlFile((XmlFile) psiFile);

                        if (missingTCount > 0) {
                            fileToMissingTCount.put(file.getPath(), missingTCount);
                        }

                        if (sumCount > 0) {
                            fileToSumCount.put(file.getPath(), sumCount);
                        }
                    }
                }
            }

            // Update UI panels
            missImCustNoPanel.update(fileToMissingTCount);
            aggCountPanel.update(fileToSumCount);
        });
    }



    private void showMissingTFields() {
        showMissingT = true;
        //updateDisplay();
    }

    private void showSumOccurrences() {
        showMissingT = false;
        //updateDisplay();
    }


    private void updateDisplay() {
        SwingUtilities.invokeLater(this::analyzeMapperXmlFiles);
    }
}